package com.heisenhub.common.redis.message;

import com.heisenhub.common.redis.annotation.RedisMessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.lang.Nullable;

/**
 * @author sen
 * @description  发布订阅
 * @date 2024/1/18 10:35
 */
public class RedisListenerProcessor implements BeanPostProcessor {

    Logger log = LoggerFactory.getLogger(RedisListenerProcessor.class);
    private RedisMessageListenerContainer redisMessageListenerContainer;

    public RedisListenerProcessor(RedisMessageListenerContainer redisMessageListenerContainer) {
        this.redisMessageListenerContainer = redisMessageListenerContainer;
    }

    @Nullable
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        RedisMessageListener redisListenerAnnotation = AnnotationUtils.findAnnotation(clazz, RedisMessageListener.class);
        if (redisListenerAnnotation != null) {
            log.info("【redis发布订阅】 :{}",clazz.getSimpleName());
            String methodName = "onMessage";
            String topic = redisListenerAnnotation.topic();
            MessageListenerAdapter adapter = new MessageListenerAdapter(bean, methodName);
            adapter.afterPropertiesSet();
            redisMessageListenerContainer.addMessageListener(adapter, new ChannelTopic(topic));
        }
        return bean;
    }
}
